<template>
  <!--size抽屉宽度（或高度）  default 378px 和 large 736px -->
  <a-drawer
      v-model:open="visible"
      ref="employeeDetailModalRef"
      class="edit-drawer modal-fixed-bottom system-auth-modal"
      root-class-name="root-customer-drawer"
      width="1000px"
      :closable="false"
      @close="onClose"
  >
    <div class="closeable" @click="onClose">{{ $t('self.closeButton') }}</div>
    <div class="modal-header">{{ title }}</div>

    <a-transfer class="customer-transfer"
        v-model:target-keys="targetKeys"
        v-model:selected-keys="selectedKeys"
        :data-source="sourceData"
        :titles="[ $t('self.transfer.title1'), $t('self.transfer.title2') ]"
        :locale="locale"
        show-search
        :filter-option="filterOption"
        @change="handleChange"
        @selectChange="handleSelectChange"
        @scroll="handleScroll"
    >
      <template
          #children="{
            direction,
            filteredItems,
            selectedKeys,
            disabled: listDisabled,
            onItemSelectAll,
            onItemSelect,
          }"
      >
        <a-table
            :pagination="direction === 'left' ? { total: sourcePagination.total, current: sourcePagination.current, pageSize: sourcePagination.pageSize }: false"
            @change="onChangePaginationPage"
            :row-selection="
            getRowSelection({
              disabled: listDisabled,
              selectedKeys,
              onItemSelectAll,
              onItemSelect,
            })
          "
            :columns="direction === 'left' ? tableLeftTableColumns : tableRightTableColumns"
            :data-source="filteredItems"
            size="small"
            :style="{ pointerEvents: listDisabled ? 'none' : null }"
            :custom-row="
            ({ key, disabled: itemDisabled }) => ({
              onClick: () => {
                if (itemDisabled || listDisabled) return;
                onItemSelect(key, !selectedKeys.includes(key));
              },
            })
          "
        />
      </template>
    </a-transfer>

    <div class="base-flex base-rows base-align-items-center base-justify-content-center footer">

      <template v-if="formState.step === 1">
        <a-button type="primary" @click="secondStep" >{{ $t('self.nextButton') }}</a-button>
        <a-button class="base-ml10" @click="onClose">{{ $t('self.cancelButton') }}</a-button>
      </template>

      <template v-else>
        <a-button @click="firstStep">{{ $t('self.previousButton') }}</a-button>
        <a-button class="base-ml10" type="primary" @click="onSubmit">{{ $t('self.submitButton') }}</a-button>
      </template>


    </div>

  </a-drawer>
</template>

<script setup>
import { computed, getCurrentInstance, onMounted, ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { mainStore } from '@/stores/mainStore'
const { proxy } = getCurrentInstance()
const $TOOL = proxy.$TOOL
const $T = proxy.$t
const $API = proxy.$API
const emit = defineEmits(['close','ok'])
const useMainStore = mainStore()

const visible = ref(false)
// 模式，add新增，show查看，edit编辑
const mode = ref('add')
const title = ref('')
// 语言包
const locale = ref({})

const targetKeys = ref([]);
const selectedKeys = ref([]);

const formState = ref({
  "id": '',               // 用户ID
  "step": 1,
  "orgIds": [],           // 选择的运营商户
  "chargeStationIds": []  // 选择的站点
})
const tableLeftTableColumns = ref([]);
const sourcePagination = ref({
  total: 0,
  current: 1,
  pageSize: 10
})
const sourceData = ref([])
const selectedData = ref([])
// 用户已选择的运营商数据
const userSelectedOrgData = ref([])

const tableRightTableColumns = ref([]);

onMounted(() => {
  resetDefaultOptionsByLang()
})

// 监听 lang 状态
watch(
    () => useMainStore.lang, // 切换语言包时
    (curr, old) => {
      // console.log('语言包', curr)
      // 获取表格列
      resetDefaultOptionsByLang()
    }
);

const getUserInfo = () => {
  $API.backend.systemUser.queryUserOrgRole.post({
    id: formState.value.id
  }).then(res => {
    const { objData } = res
    userSelectedOrgData.value = objData.orgList
    // if(formState.value.step === 1) {
    //   selectedData.value = userSelectedOrgData.value
    //   targetKeys.value = userSelectedOrgData.value.map(ele => {
    //     return ele.id
    //   })
    // }
    // console.log(selectedData.value)
    // console.log(objData)
  }).catch(err => {
    console.log(err)
    message.error(err.msg);
  })
}


const firstStep = () => {
  title.value = $T('self.systemUser.tips15')
  // targetKeys.value = formState.value.orgIds
  // selectedKeys.value = formState.value.orgIds
  formState.value.step = 1
  tableLeftTableColumns.value = [
    // {
    //   dataIndex: 'id',
    //   key: 'id',
    //   title: $T('self.systemUser.tips16'),
    // },
    {
      key: 'orgName',
      dataIndex: 'orgName',
      title: $T('self.systemUser.tips17'),
    }
  ]
  tableRightTableColumns.value = [
    {
      dataIndex: 'orgName',
      title: $T('self.systemUser.tips17'),
    }
  ]
  // console.log('已选择的运营商ID', selectedKeys.value)
  // 获取运营商列表
  getOrgList()
}
const secondStep = () => {
  // console.log('选择的运营商ID', formState.value.orgIds)
  title.value = $T('self.systemUser.tips18')
  targetKeys.value = selectedKeys.value = []  // 清空已选择项
  selectedData.value = []                     // 清空已选择项附加

  formState.value.step = 2
  sourceData.value = [] // 清空表格数据
  sourcePagination.value.current = 1  // 恢复第一页

  tableLeftTableColumns.value = [
    {
      key: 'stationName',
      dataIndex: 'stationName',
      title: $T('self.systemUser.tips20'),
    }
  ]
  tableRightTableColumns.value = [
    {
      dataIndex: 'stationName',
      title: $T('self.systemUser.tips20'),
    }
  ]

  // console.log('已选择的站点ID',selectedKeys.value)
  // 获取站点列表
  getStationList()
}

const getOrgList = () => {
  $API.backend.operators.list.get({
    pageNo: sourcePagination.value.current
  }).then(res => {
    const { objData } = res
    sourcePagination.value.total = objData.totalCount
    // sourcePagination.value.current = objData.pageNo
    sourceData.value = objData.data.map(item => {
      return {
        ...item,
        key: item.id.toString(),
      }
    })
    sourceData.value = sourceData.value.concat(selectedData.value)
    // console.log('来源', sourceData.value)
  }).catch((err) => {
    message.error(err.msg);
  })
}
const getStationList = () => {
  $API.backend.businessStation.list.post({
    pageNo: sourcePagination.value.current
  }).then(res => {
    const { objData } = res
    sourcePagination.value.total = objData.totalCount
    // sourcePagination.value.current = objData.pageNo
    sourceData.value = objData.data.map(item => {
      return {
        ...item,
        key: item.id.toString()
      }
    })
    sourceData.value = sourceData.value.concat(selectedData.value)
    // console.log(selectedKeys.value)
    // console.log('来源', sourceData.value)
  }).catch((err) => {
    message.error(err.msg);
  })

}

const resetDefaultOptionsByLang = () => {
  locale.value = {
    itemUnit: $T('self.transfer.itemUnit'),
    itemsUnit: $T('self.transfer.itemsUnit'),
    notFoundContent: $T('self.transfer.notFoundContent'),
    searchPlaceholder: $T('self.transfer.searchPlaceholder')
  }
}
const filterOption = (inputValue, option) => {
  return option.description.indexOf(inputValue) > -1;
};
const getRowSelection = ({ disabled, selectedKeys, onItemSelectAll, onItemSelect }) => {
  return {
    getCheckboxProps: item => ({
      disabled: disabled || item.disabled,
    }),
    onSelectAll(selected, selectedRows) {
      const treeSelectedKeys = selectedRows.filter(item => !item.disabled).map(({ key }) => key);
      onItemSelectAll(treeSelectedKeys, selected);
    },
    onSelect({ key }, selected) {
      onItemSelect(key, selected);
    },
    selectedRowKeys: selectedKeys,
  };
};
// 分页
const onChangePaginationPage = (pagination) => {
  const { current, pageSize, total } = pagination
  sourcePagination.value.current = current
  sourcePagination.value.pageSize = pageSize
  if(formState.value.step === 1) {
    // 获取运营商列表
    getOrgList()
  }else{
    // 获取站点列表
    getStationList()
  }
  // console.log(pagination)
  // tableCurrentPage.value = current
}
const handleChange = (nextTargetKeys, direction, moveKeys) => {
  if(formState.value.step === 1) {
    formState.value.orgIds = nextTargetKeys
  }else if(formState.value.step === 2) {
    formState.value.chargeStationIds = nextTargetKeys
  }
  selectedData.value = sourceData.value.filter(item => nextTargetKeys.includes(item.key));
  // console.log('targetKeys: ', nextTargetKeys);
  // console.log('direction: ', direction);
  // console.log('moveKeys: ', moveKeys);
}
const handleSelectChange = (sourceSelectedKeys, targetSelectedKeys) => {
  // console.log('sourceSelectedKeys: ', sourceSelectedKeys);
  // console.log('targetSelectedKeys: ', targetSelectedKeys);
};
const handleScroll = (direction, e) => {
  // console.log('direction:', direction);
  // console.log('target:', e.target);
};

const onSubmit = () => {
  // console.log(formState.value)
  $API.backend.systemUser.saveAuth.post({
    id: formState.value.id,
    orgList: { orgId: formState.value.orgIds },
    stationUserList: { stationId: formState.value.chargeStationIds }
  }).then(res => {

    message.success($T('self.message.success'))
    onReset()
    visible.value = false
    emit('ok')

    // console.log('来源', sourceData.value)
  }).catch((err) => {
    message.error(err.msg);
  })

};

const onReset = () => {
  // 清空内容
  formState.value = {
    "id": '',
    "step": 1,
    "orgIds": [],           // 选择的运营商户
    "chargeStationIds": []  // 选择的站点
  }
  targetKeys.value = selectedKeys.value = []  // 清空已选择项
  selectedData.value = []                     // 清空已选择项附加
}

const onClose = () => {
  onReset()
  visible.value = false
  emit('close')
}

const edit = (record) => {
  mode.value = 'edit'
  visible.value = true
  formState.value.id = record.id
  targetKeys.value = selectedKeys.value = [] // 清空已选择项
  selectedData.value = []                    // 清空已选择项附加
  firstStep()
  getUserInfo()
  // $TOOL.array.cloneExistKey(formState.value, detail.value)
  // console.log(formState.value)
}

// 子组件中要通过defineExpose将方法暴露给父组件
defineExpose({
  edit,
})
</script>

<style lang="scss" scoped>
.edit-drawer {
  position: relative;
  .closeable {
    @include closeable;
  }


}

</style>
